package com.digitalchina.lxnsy.activity.old;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.WinningListAdapter;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.api.BusinessLottery;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.PrizeVO;
import com.digitalchina.lxnsy.entity.WinningVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.ToastUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/3/23 10:43
 * 修改备注：
 * ================================================
 */
public class IntegralLotteryActivity extends BaseActivity {

    @Bind(R.id.integral_lottery_sv1)
    SimpleDraweeView integralLotterySv1;
    @Bind(R.id.integral_lottery_sv2)
    SimpleDraweeView integralLotterySv2;
    @Bind(R.id.integral_lottery_sv3)
    SimpleDraweeView integralLotterySv3;
    @Bind(R.id.integral_lottery_sv4)
    SimpleDraweeView integralLotterySv4;
    @Bind(R.id.integral_lottery_sv5)
    SimpleDraweeView integralLotterySv5;
    @Bind(R.id.integral_lottery_sv6)
    SimpleDraweeView integralLotterySv6;
    @Bind(R.id.integral_lottery_sv7)
    SimpleDraweeView integralLotterySv7;
    @Bind(R.id.integral_lottery_sv8)
    SimpleDraweeView integralLotterySv8;
    @Bind(R.id.integral_lottery_sv9)
    SimpleDraweeView integralLotterySv9;
    @Bind(R.id.integral_lottery_sv10)
    SimpleDraweeView integralLotterySv10;

    @Bind(R.id.integral_lottery_iv_start)
    ImageView integralLotteryIvStart;  // 抽奖按钮

    @Bind(R.id.integral_lottery_lv_winners)
    ListView integralLotteryLvWinners; // 中奖人列表


    @Bind(R.id.integral_lottery_iv1)
    ImageView integralLotteryIv1;
    @Bind(R.id.integral_lottery_iv2)
    ImageView integralLotteryIv2;
    @Bind(R.id.integral_lottery_iv3)
    ImageView integralLotteryIv3;
    @Bind(R.id.integral_lottery_iv4)
    ImageView integralLotteryIv4;
    @Bind(R.id.integral_lottery_iv5)
    ImageView integralLotteryIv5;
    @Bind(R.id.integral_lottery_iv6)
    ImageView integralLotteryIv6;
    @Bind(R.id.integral_lottery_iv7)
    ImageView integralLotteryIv7;
    @Bind(R.id.integral_lottery_iv8)
    ImageView integralLotteryIv8;
    @Bind(R.id.integral_lottery_iv9)
    ImageView integralLotteryIv9;
    @Bind(R.id.integral_lottery_iv10)
    ImageView integralLotteryIv10;

    @Bind(R.id.act_integral_lottery_content)
    LinearLayout integralLotteryContent;
    @Bind(R.id.tv_chance_num)
    TextView tvChanceNum;
    @Bind(R.id.tv_my_prize)
    TextView tvMyPrize;
    @Bind(R.id.tv_rule)
    TextView tvRule;

    private List<ImageView> layerList = new ArrayList<>();
    public static final int MESSAGE_STOP = 999;

    private List<PrizeVO> prizeVOList = new ArrayList<>();
    private List<SimpleDraweeView> simpleDraweeViewList = new ArrayList<>();
    private List<WinningVO> winningVOList = new ArrayList<>();


    private int whatTag;
    private int number;
    private int mIndex;

    private int mType; // 中奖类型

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_integral_lottery);
        setTitle("幸运大转盘");
        setRightText("分享");
    }

    @Override
    public void initMember() {

        initPrizeList();
        getNetData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 查询剩余抽奖次数
        if (Utils.isLogin(this)) {
            BusinessLottery.queryLotteryNum(this, mHandler);
        }
    }

    /**
     * 获取奖品信息
     */
    private void getNetData() {
        BusinessLottery.getPrizeList(this, mHandler);
    }

    /**
     * 初始化图层
     */
    private void initPrizeList() {
        layerList.add(integralLotteryIv1);
        layerList.add(integralLotteryIv2);
        layerList.add(integralLotteryIv3);
        layerList.add(integralLotteryIv4);
        layerList.add(integralLotteryIv5);
        layerList.add(integralLotteryIv6);
        layerList.add(integralLotteryIv7);
        layerList.add(integralLotteryIv8);
        layerList.add(integralLotteryIv9);
        layerList.add(integralLotteryIv10);

        simpleDraweeViewList.add(integralLotterySv1);
        simpleDraweeViewList.add(integralLotterySv2);
        simpleDraweeViewList.add(integralLotterySv3);
        simpleDraweeViewList.add(integralLotterySv4);
        simpleDraweeViewList.add(integralLotterySv5);
        simpleDraweeViewList.add(integralLotterySv6);
        simpleDraweeViewList.add(integralLotterySv7);
        simpleDraweeViewList.add(integralLotterySv8);
        simpleDraweeViewList.add(integralLotterySv9);
        simpleDraweeViewList.add(integralLotterySv10);

    }

    @Override
    public void addListener() {

        tvMyPrize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GotoUtil.gotoActivity(IntegralLotteryActivity.this, MyPrizeListActivity.class);
            }
        });

        tvRule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = URL.URL_LOTTERY_RULE;
                Map<String, String> map = new HashMap<>();
                map.put("url", url);
                map.put("title", "活动规则");
                GotoUtil.gotoActivity(IntegralLotteryActivity.this, WebViewActivity.class, "map", map);
            }
        });
    }

    @Override
    public void setHandler() {

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                whatTag = msg.what;
                if (isFinishing())
                    return;
                switch (msg.what) {
                    case 0:
                        setTextColor(0);
                        break;
                    case 1:
                        setTextColor(1);
                        break;
                    case 2:
                        setTextColor(2);
                        break;
                    case 3:
                        setTextColor(3);
                        break;
                    case 4:
                        setTextColor(4);
                        break;
                    case 5:
                        setTextColor(5);
                        break;
                    case 6:
                        setTextColor(6);
                        break;
                    case 7:
                        setTextColor(7);
                        break;
                    case 8:
                        setTextColor(8);
                        break;
                    case 9:
                        setTextColor(9);
                        break;

                    case MESSAGE_STOP:
                        integralLotteryIvStart.setClickable(true);
                        showPrize(mType);
                        break;
                    case MSG.MSG_GET_PRIZE_LIST_SUCCESS:
                        // 奖品信息获取到了后把抽奖按钮设置成可点击状态
                        integralLotteryIvStart.setClickable(true);
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_PRIZE_LIST_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_QUERY_LOTTERY_NUM_SUCCESS:
                        String lotteryNum = FastJsonUtil.getString(msg.obj.toString(), "lotteryNum");
                        if (StringUtil.isStrEmpty(lotteryNum))
                            lotteryNum = "0";
                        tvChanceNum.setText(lotteryNum);
                        break;
                    case MSG.MSG_DRAW_PRIZE_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_DRAW_PRIZE_FIELD:
                        if (msg.arg1 == 999003) {
                            showPrize(2);
                        } else
                            showToast(msg.obj.toString());
                        break;
                }
            }

            /**
             * 展示抽奖结果
             * showType   0-已中奖   1-未中奖  2-无抽奖次数
             */
            private void showPrize(int type) {


                switch (type) {
                    case 0:
                        lotteryDialog(IntegralLotteryActivity.this, 0, prizeVOList.get(mIndex).getPrizeName());
                        break;
                    case 1:
                        lotteryDialog(IntegralLotteryActivity.this, 1, "");
                        break;
                    case 2:
                        lotteryDialog(IntegralLotteryActivity.this, 2, "");
                        break;
                }
            }


            private void setTextColor(int index) {


                for (int i = 0; i < layerList.size(); i++) {
                    if (i == index) {
                        layerList.get(i).setVisibility(View.VISIBLE);
                    } else {
                        layerList.get(i).setVisibility(View.GONE);
                    }
                }
            }
        };

    }

    /**
     * 抽奖弹出框
     *
     * @param poActivity
     * @param showType   0-已中奖   1-未中奖  2-无抽奖次数
     * @param prizeName
     */
    public void lotteryDialog(final Activity poActivity, final int showType, String prizeName) {

        final android.app.AlertDialog loDialog = new android.app.AlertDialog.Builder(poActivity)
                .create();
        LayoutInflater loInflater = poActivity.getLayoutInflater();
        loDialog.setView(loInflater.inflate(
                R.layout.dialog_lottery, null));
        loDialog.show();
        loDialog.getWindow().setGravity(Gravity.CENTER);
        loDialog.getWindow().setLayout(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        loDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        loDialog.getWindow().setContentView(
                R.layout.dialog_lottery);
        loDialog.setCanceledOnTouchOutside(false);
        loDialog.setCancelable(false);

        ImageView ivTitle =  loDialog.findViewById(R.id.dialog_lottery_iv_title);
        ImageView ivBackground =  loDialog.findViewById(R.id.dialog_lottery_iv_background);
        TextView tvPrize =  loDialog.findViewById(R.id.dialog_lottery_tv_prize_name);
        TextView tvLeft =  loDialog.findViewById(R.id.dialog_lottery_tv_button_left);
        TextView tvRight =  loDialog.findViewById(R.id.dialog_lottery_tv_button_right);


        switch (showType) {
            case 0: // 用户中奖
                ivTitle.setImageResource(R.drawable.bg_lottery_congratulation_title);
                ivBackground.setImageResource(R.drawable.bg_lottery_congratulation);
                tvPrize.setText("恭喜抽中：\n" + prizeName);
                tvLeft.setText("继续抽奖");
                tvRight.setText("查看奖品");
                break;
            case 1: // 用户未中奖
                ivTitle.setImageResource(R.drawable.bg_lottery_regret_title);
                ivBackground.setImageResource(R.drawable.bg_lottery_regret);
                tvPrize.setText("再接再厉，再来一次吧！");
                tvLeft.setText("再来一次");
                tvRight.setText("稍后继续");
                break;
            case 2: // 无抽奖次数
                ivTitle.setImageResource(R.drawable.bg_lottery_shortage_title);
                ivBackground.setImageResource(R.drawable.bg_lottery_shortage);
                tvPrize.setText("分享活动至微信、QQ，\n免费得抽奖机会！");
                tvLeft.setText("去分享");
                tvRight.setText("返回");
                break;
        }


        tvLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loDialog.dismiss();
            }
        });

        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (showType == 0)
                    GotoUtil.gotoActivity(poActivity, MyPrizeListActivity.class);
                loDialog.dismiss();
            }
        });
    }

    @Override
    public void callBack(Object object) {

        switch (whatTag) {
            case MSG.MSG_GET_PRIZE_LIST_SUCCESS:
                prizeVOList = FastJsonUtil.getListBean(object.toString(), "body", "prizeInfoList", PrizeVO.class);
                winningVOList = FastJsonUtil.getListBean(object.toString(), "body", "exchangeHistVOS", WinningVO.class);
                String activityState = FastJsonUtil.getString(object.toString(), "activityState");

                if (activityState == null || !activityState.equals("0")) {

                    new MaterialDialog.Builder(this)
                            .title("提示")
                            .content("暂无任何抽奖信息")
                            .positiveText("确定")
                            .cancelable(false)
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    finish();
                                }
                            })
                            .show();
                } else {
                    if (prizeVOList != null)
                        setPrizeImage();
                    if (winningVOList != null)
                        setWinningList();
                }

                break;
            case MSG.MSG_DRAW_PRIZE_SUCCESS:

                String index = FastJsonUtil.getBean(object.toString(), "index", String.class);
                String lotteryNum = FastJsonUtil.getBean(object.toString(), "lotteryNum", String.class);

                tvChanceNum.setText(lotteryNum + "");

                if (index != null) {
                    for (int i = 0; i < prizeVOList.size(); i++) {
                        if (index.equals(prizeVOList.get(i).getIndex())) {
                            mIndex = i;
                            if (prizeVOList.get(i).getPrizeGrade() == 8) // 谢谢惠顾奖
                                mType = 1;
                            else
                                mType = 0;
                            break;
                        }
                    }

                    drawLottery(mIndex);
                }

                break;
        }

    }

    /**
     * 设置中奖人
     */
    private void setWinningList() {
        WinningListAdapter winningListAdapter = new WinningListAdapter(this, winningVOList);
        integralLotteryLvWinners.setAdapter(winningListAdapter);
    }

    /**
     * 设置奖品图片
     */
    private void setPrizeImage() {

        for (int i = 0; i < prizeVOList.size(); i++) {
            FrescoUtil.showImageSmall(prizeVOList.get(i).getImg(), simpleDraweeViewList.get(i));
        }
    }


    @OnClick({R.id.integral_lottery_iv_start, R.id.integral_lottery_rl_winners})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.integral_lottery_iv_start:
                //先判断是否登录
                if (!Utils.isLogin(IntegralLotteryActivity.this)) {
                    GotoUtil.gotoActivity(IntegralLotteryActivity.this, LoginGuideActivity.class);
                } else
                    drawPrize();
                break;
            case R.id.integral_lottery_rl_winners:

                break;
        }
    }

    /**
     * 调用抽奖接口
     */
    private void drawPrize() {

        BusinessLottery.drawPrize(this, mHandler);
    }

    String title = "快来农科专家玩幸运大转盘！";
    String content = "一亩地全年水溶肥，一亩地全年涂杆肥，50元话费，20元代金券，众多好礼等你抢！";
    String shareUrl = URL.URL_SHARE_LOTTERY;
    String imgUrl = URL.SERVER + "static/img/dzp.png";

    @Override
    public void rightOnClick() {
    }


    private void drawLottery(final int index) {

        integralLotteryIvStart.setClickable(false);
        number = 0;
        new Thread(new Runnable() {
            public void run() {
                while (number < 41 + index) {
                    Message message = new Message();
                    switch (number % 10) {
                        case 0:
                            message.what = 0;
                            break;
                        case 1:
                            message.what = 1;
                            break;
                        case 2:
                            message.what = 2;
                            break;
                        case 3:
                            message.what = 3;
                            break;
                        case 4:
                            message.what = 4;
                            break;
                        case 5:
                            message.what = 5;
                            break;
                        case 6:
                            message.what = 6;
                            break;
                        case 7:
                            message.what = 7;
                            break;
                        case 8:
                            message.what = 8;
                            break;
                        case 9:
                            message.what = 9;
                            break;
                        default:
                            break;
                    }
                    number++;
                    mHandler.sendMessage(message);
                    if (number < 30) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else if (number >= 30 && number < 41) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }

                Message message = new Message();
                message.what = MESSAGE_STOP;
                message.obj = index + 1;
                mHandler.sendMessage(message);
            }
        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
